BASEDIR=`dirname ${0}`
. ${BASEDIR}/config-vars.sh
PATH=$NODE_HOME/bin:$PATH
case "$1" in
  "start")
    if [ x${NODE_HOME} = "x" ]; then
      echo "NODE_HOME does not appear to be in your environment."
      echo "You must define the NODE_HOME environment variable"
      echo "in the ${BASEDIR}/config-vars.sh shell script"
      exit 1
    else
      if [ ! -e ${NODE_HOME}/bin/node ]; then
        echo "NODE_HOME is defined, but the 'node' executable"
        echo "cannot be found in:  "
        echo ""
        echo "${NODE_HOME}/bin"
        echo ""
        echo "This is a fatal error."
        echo "Verify your NODE_HOME environment variable is set"
        echo "in ${BASEDIR}/config-vars.sh"
        exit 1
      fi
    fi

    echo "Starting  Server.. "
    cd ${BASEDIR}
    npm run clean
    npm run tsc
    EGG_SERVER_ENV=prod npm start $NPM_START_ATTRS
    if [ $? -ne 0 ]; then
      "app launch failed.  Exiting."
      exit 1
    else
      echo "ok"
    fi
  ;;
  "stop")
    echo "Stopping  Server.. "
    cd ${BASEDIR}
    npm stop $NPM_STOP_ATTRS
    echo "ok"
  ;;
  "restart")
    if [ x${NODE_HOME} = "x" ]; then
      echo "NODE_HOME does not appear to be in your environment."
      echo "You must define the NODE_HOME environment variable"
      echo "in the ${BASEDIR}/config-vars.sh shell script"
      exit 1
    else
      if [ ! -e ${NODE_HOME}/bin/node ]; then
        echo "NODE_HOME is defined, but the 'node' executable"
        echo "cannot be found in:  "
        echo ""
        echo "${NODE_HOME}/bin"
        echo ""
        echo "This is a fatal error."
        echo "Verify your NODE_HOME environment variable is set"
        echo "in ${BASEDIR}/config-vars.sh"
        exit 1
      fi
    fi

    cd ${BASEDIR}
    echo "build"
    npm run clean
    npm run tsc
    echo "Stopping  Server.. "
    cd ${BASEDIR}
    npm stop $NPM_STOP_ATTRS
    echo "ok"
    echo "Starting  Server.. "
    EGG_SERVER_ENV=prod npm start $NPM_START_ATTRS
    if [ $? -ne 0 ]; then
      "app launch failed.  Exiting."
      exit 1
    else
      echo "ok"
    fi
  ;;
  *)
    echo "Usage: ${0} {start|stop|restart}"
  ;;
esac